package com.webull.information.center.carwler.job;

import java.net.InetAddress;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.webull.information.center.carwler.common.model.CollectRecord;
import com.webull.information.center.carwler.common.model.parm.CollectParm;
import com.webull.information.center.carwler.common.util.NewsCcUtil;
import com.webull.information.center.carwler.common.util.eljob.ElasticJobUtil;
import com.webull.information.center.carwler.dao.CollectRecordDao;
import com.webull.information.center.carwler.task.News_YahooFullStock_Task;
import com.webull.securities.client.model.Exchange;
import com.webull.securities.client.model.parm.ExchangeParam;
import com.webull.securities.client.service.ExchangeService;

/**
 * 雅虎聚合新闻采集
 * 
 * @author shimingjun
 * @date 2017年3月7日 下午1:40:25
 * @version 1.0
 * @since JDK 1.8
 */
@Component
public class News_YahooFullStock_Job implements SimpleJob {
	protected final Logger logger = LogManager.getLogger(getClass());
	private @Autowired News_YahooFullStock_Task fullStockFinanceNews;
	private @Autowired ExchangeService exchangeService;
	private @Autowired CollectRecordDao collectRecordDao;
	private final String collectJob = "News_YahooFullStock_Job";
	private final Integer loop = 50;// 循环20次退出,获取 20*100

	@Override
	public void execute(ShardingContext context) {
		int sharding = Optional.ofNullable(context).map(v -> v.getShardingItem()).orElse(-1);
		int totalCount = Optional.ofNullable(context).map(v -> v.getShardingTotalCount()).orElse(-1);

		logger.info("News_YahooFullStock_Job start:" + ArrayUtils.toString(sharding) + ",totalCount:" + totalCount);
		List<Exchange> exchanges = exchangeService.search(new ExchangeParam());
		logger.info("News_YahooFullStock_Job div size{};exchanges:{};", exchanges != null ? exchanges.size() : 0,
				ArrayUtils.toString(exchanges));
		List<Exchange> shardExchanges = Optional.ofNullable(ElasticJobUtil.shardingItems(context, exchanges))
				.orElse(exchanges);

		process_0(shardExchanges);
	}


	public void process_0(List<Exchange> shardExchanges) {
		Collections.shuffle(shardExchanges);
		/**
		 * 强制把96排前面
		 */
		NewsCcUtil.foreSortExchange("2017-05-08",shardExchanges,96);

		logger.info("News_YahooFullStock_Job div size{};shardExchanges:{};",
				shardExchanges != null ? shardExchanges.size() : 0, ArrayUtils.toString(shardExchanges));
		for (int i = 0; shardExchanges != null && i < shardExchanges.size(); i++) {
			try {
				List<CollectRecord> records = collectRecordDao.search(collectParm(shardExchanges.get(i)));
				Integer lastId = getLastTickeId(records);
				logger.info("News_YahooFullStock_Job shardExchanges start collectJob{} div ,exchange:{},lastId{}",
						collectJob, shardExchanges.get(i).getExchangeCode(), lastId);
				Integer lastId_ = fullStockFinanceNews
						.News_YahooFullStock_TaskExchangeCode(shardExchanges.get(i).getExchangeCode());
				CollectRecord record = backRecord(shardExchanges.get(i));
				record.setLastTickerId(lastId_);
				Integer collId = collectRecordDao.add(record);
				logger.info("News_YahooFullStock_Job shardExchanges end collectJob{} div ,exchange:{},collId{}",
						collectJob, shardExchanges.get(i).getExchangeCode(), collId);
			} catch (Exception e) {
				logger.error("News_YahooFullStock_Job shardExchanges collectJob div error:" + shardExchanges.get(i), e);
			}

		}
	}

	private Integer getLastTickeId(List<CollectRecord> records) {
		if (records == null || records.isEmpty()) {
			return -1;
		} else {
			return records.get(0).getLastTickerId();
		}
	}

	private CollectParm collectParm(Exchange exchange) {
		CollectParm parm = new CollectParm();
		parm.setCollectJob(collectJob);
		parm.setExchangeCode(exchange.getExchangeCode());
		parm.setExchangeId(exchange.getId());
		parm.setRecordType(CollectRecord.RecordTypeConstants.NEWS);
		return parm;
	}

	private CollectRecord backRecord(Exchange exchange) {
		CollectRecord record = new CollectRecord();
		record.setCollectJob(collectJob);
		record.setExchangeCode(exchange.getExchangeCode());
		record.setExchangeId(exchange.getId());
		record.setRecordType(CollectRecord.RecordTypeConstants.NEWS);
		try {
			record.setCustomer(InetAddress.getLocalHost().getHostAddress());
		} catch (Exception e) {
		}
		return record;
	}

}
